
package urnoted;
import java.awt.*;
import java.awt.event.*;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JButton;
import javax.swing.border.*;

import urnoted.Controller;



public class Key extends JButton {
    private static final int WIDTH = 48;
    private static final int HEIGHT = 280;
    private static final int BW2 = 14;      // half the width of black keys
    private static final int BH = 184;      // the height of black keys
    private static final Dimension DIMENSION = new Dimension(WIDTH, HEIGHT);
    private static final Border BORDER = new LineBorder(Color.BLACK, 1);
    private Controller controller;
    private int index;    //  index in the keyboardPanel's keys list
    private String name;  // e.g., "B4"
    
    private Color keyColor;

    private Timer timer = new Timer();
    
    public Key(final Controller controller, int index, String name) {
        this.controller = controller;
        this.index = index;
        this.name = name;
        this.addActionListener(new ActionListener(){  // anonomous inner class
            @Override
            public void actionPerformed(ActionEvent event) {
                setCurrentKey();
            }
        });
        this.setPreferredSize(DIMENSION);
        this.setBorder(BORDER);
        keyColor = Color.WHITE;
        this.setBackground(keyColor);
    }

    @Override
    protected void paintComponent(Graphics g) {  // draw black keys  
        super.paintComponent(g);
        g.setColor(keyColor);
        
        g.fillRect(0,0,getWidth(),getHeight());
        g.setColor(Color.BLACK);
        
        // Draw black keys:
        char ch = name.charAt(0);  // e.g., 'B'
        if (ch == 'B' || ch == 'E') {
            g.fillRect(0, 0, BW2, BH);
        } else if (ch == 'C' || ch == 'F') {
            g.fillRect(this.getWidth()-BW2, 0, BW2, BH);
        } else {
            g.fillRect(0, 0, BW2, BH);
            g.fillRect(this.getWidth()-BW2, 0, BW2, BH);
        }
        
        // Draw name:
        String label = name.substring(0, 1);
        g.setFont(new Font("Arial Bold", Font.BOLD, 40));
        g.drawString(label, 11, HEIGHT+8);
    }

    public void setKeyColor(Color c)
    {
    	keyColor = c;
    }
    
    public int getIndex() {
        return index;
    }

    public String getName() {
        return name;
    }

    private void setCurrentKey() {
        controller.setCurrentKey(this);
    }

    void clearAfterMilli(long l) {
        this.timer.schedule(new PaintTask(), l);
    }
    
    class PaintTask extends TimerTask{
        public PaintTask() {

        }

        @Override
        public void run() {
            Key.this.setKeyColor(Color.white);
            repaint();
            this.cancel();
        }
    }
}
